#!/bin/bash
#
# Transport that uses the curl(1) command to transfer files
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 20 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


declare -g CURL_PROTOLIST="dict file ftp ftps gopher http https imap imaps "
CURL_PROTOLIST+="ldap ldaps pop3 pop3s rtmp rtsp scp sftp smtp smtps "
CURL_PROTOLIST+="telnet tftp "


## p_transport_curl_can_download <url>
##
## Determines if the curl transport can download <url>. Returns 0 if the
## transport is able to handle the <url>, non-zero otherwise.
##
function p_transport_curl_can_download() {
	local status=0
	local chk=
	local filename=
	
	which curl > /dev/null 2>&1
	status=$?
	
	if [[ ${status} -eq 0 ]]; then
		# Have the curl(1) command: see if it can handle this type of URL
		status=1
		for proto in ${CURL_PROTOLIST}; do
			chk=$(echo "$1" | grep ^${proto}://)
			if [[ -n "${chk}" ]]; then
				status=0
				break
			fi
		done
	fi
	
	return ${status}
}


## p_transport_curl_download <url> <output file> <user agent>
##
## Downloads a file from <url> to <output file>. If <output file> is the
## special name "-", downloads the file to standard output instead. The
## <user agent> specifies the user agent string to report when downloading.
## Returns 0 on success, non-zero if an error occurs.
##
function p_transport_curl_download() {
	local status=0
	
	if [[ "$2" != "-" ]]; then
		# Test writability of the output file before proceeding
		touch "$2"
		status=$?
	
		if [[ ${status} -eq 0 ]]; then
			# Clobber the output file to avoid curl failing
			if [[ "$2" != "-" ]]; then
				rm -f -- "$2"
				status=$?
			fi
		else
			echo "Cannot download to $2 (cannot create output file)"
		fi
	fi
	
	if [[ ${status} -eq 0 ]]; then
		curl --user-agent "$3" -L -o "$2" "$1"
		status=$?
	fi
	
	return ${status}
}
